Charting dates with Matplotlib

by: Chill59, 8 years ago

Last edited: 8 years ago

Following the Matplotlib tutorial, I tried to import a csv file and graph the data (year, count).  Everything works fine with the exception that the x-axis doesn't show years (2008 - 2015).  Rather, the x-axis seems to be displaying the index numbers for the imported dataframe.  Any suggestions? Here is my code:


# Graph data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df_annual_lang = pd.read_csv('annual_lang_count.csv', names =['year', 'count'])

x = df_annual_lang['year']
y = df_annual_lang['count']
plt.plot(x, y)
plt.xlabel('Years')
plt.ylabel('Count of Languages in Use')
plt.title('Number of Languages in Use: 2008-2015')
plt.show()




You must be logged in to post. Please login or register an account.



You'd need to convert the year to a datetime if it's not one for sure, http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html

-Harrison 8 years ago

You must be logged in to post. Please login or register an account.

Many thanks!  In the end, I found that including 'parse_dates' worked (although I'm not entirely sure why it works):

df_annual_lang = pd.read_csv('annual_lang_count.csv', parse_dates=['year'], names =['year', 'count'])



-Chill59 8 years ago

You must be logged in to post. Please login or register an account.


parse_dates just automatically uses the datetime parser to look for dates. If found, it'll treat your column as a datetime object, which can then be easily recognized by matplotlib.

-Harrison 8 years ago

You must be logged in to post. Please login or register an account.


Ok, I see. Thanks again!

-Chill59 8 years ago

You must be logged in to post. Please login or register an account.